import React, {Component} from 'react';
import {
  StyleSheet,
  Appearance,
  StatusBar,
  Text,
  View,
  ScrollView,
  Image,
  Modal,
  TouchableOpacity,
  TextInput,
} from 'react-native';
import {connect} from 'react-redux';
import HTMLView from 'react-native-htmlview';
import ImageViewer from 'react-native-image-zoom-viewer';
import {Toast, Icon} from '@ant-design/react-native';
import {dark, light, baseURL} from '../../config';
import PageHeader from '../../components/PageHeader';
import UserHeader from '../../components/UserHeader';
import {getJfArticleDetail} from '../../api/article';
import {pxToDp} from '../../utils/stylesKits';
import {downloadFile} from '../../utils/downloadFile';

/**
 * APP ArticleDetali 页面
 * @colorScheme 用户手机主题模式 是否开启了黑夜模式
 * */
const colorScheme = Appearance.getColorScheme() === 'dark' ? dark : light;

class ArticleDetali extends Component {
  constructor(props) {
    super(props);
    this.state = {
      articleDetali: {},
      html_content: {},
      user: {},
      images: [],
      modalVisible: false,
      imageViewerIndex: 0,
    };
  }

  getJfArticleDetail = async () => {
    const {route} = this.props;
    const params = {
      id: route.params.articleId,
    };
    const res = await getJfArticleDetail(params);
    if (res.data) {
      this.setState(() => {
        return {
          articleDetali: res.data,
          html_content: res.data.html_content,
          user: res.data.user,
        };
      });
    }
  };

  /**
   * 搜索子结点找出图片
   *
   */
  renderChildren = (node, index) => {
    if (node.name === 'img') {
      const attr = node.attribs;
      const {images} = this.state;
      images.push({url: attr.src});
      return (
        <TouchableOpacity
          key={index}
          onPress={() => this.showImageViewer(attr.src)}>
          <Image style={styles.articleImage} source={{uri: attr.src}} />
        </TouchableOpacity>
      );
    } else {
      if (node.children) {
        return (
          <View key={index}>
            {node.children.map((item, i) => this.renderChildren(item, i))}
          </View>
        );
      } else {
        return <Text key={index}>{node.data}</Text>;
      }
    }
  };

  /**
   *  渲染html 字符串
   */
  renderNode = (node, index, siblings, parent, defaultRenderer) => {
    if (node.name === 'img') {
      return <Text key={index}>tutu</Text>;
    } else {
      if (node.children) {
        return (
          <View key={index}>
            {node.children.map((item, i) => this.renderChildren(item, i))}
          </View>
        );
      } else {
        return <Text key={index}>{node.data}</Text>;
      }
    }
  };

  hideImageViewer = () => this.setState(() => ({modalVisible: false}));

  showImageViewer = async url => {
    const {images} = this.state;
    const index = images.findIndex(item => item.url === url);
    await this.setState(() => ({imageViewerIndex: index}));
    this.setState(() => ({modalVisible: true}));
  };

  componentDidMount() {
    this.getJfArticleDetail();
  }

  componentDidUpdate(prevProps, prevState) {}

  componentWillUnmount() {}

  render() {
    const {
      articleDetali,
      html_content,
      user,
      modalVisible,
      images,
      imageViewerIndex,
    } = this.state;
    return (
      <View style={styles.container}>
        <StatusBar
          backgroundColor="transparent"
          barStyle={colorScheme.barStyle}
          translucent={true}
        />
        <PageHeader
          title={articleDetali.title}
          style={{backgroundColor: colorScheme.backgroundColor}}
        />
        {/* 文章主要内容区域 */}
        <ScrollView style={styles.articleDetali}>
          <UserHeader user={user} />
          {html_content.content ? (
            <HTMLView
              value={html_content.content}
              renderNode={this.renderNode}
            />
          ) : (
            <Text />
          )}
          <Text />
        </ScrollView>
        {/* 文章主要内容区域 */}
        <View style={styles.comment}>
          <TextInput
            style={styles.commentInput}
            value={'输入评论...'}
            editable={false}
          />
          <View style={styles.like}>
            <Icon name="like" style={styles.likeIcon} />
            <Text>66</Text>
          </View>
          <View style={styles.like}>
            <Icon name="comment" style={styles.likeIcon} />
            <Text>29</Text>
          </View>
        </View>
        {/* 图片查看 Modal */}
        <Modal
          animationType="fade"
          visible={modalVisible}
          onRequestClose={this.hideImageViewer}>
          <ImageViewer
            index={imageViewerIndex}
            imageUrls={images}
            style={styles.imageModal}
            enableSwipeDown={true}
            onSave={url => downloadFile(url)}
            menuContext={{saveToLocal: '保存图片', cancel: '取消'}}
            onClick={this.hideImageViewer}
          />
        </Modal>
        {/* 图片查看 Modal */}
      </View>
    );
  }
}

const mapStateToProps = state => ({});
const mapDispatchToProps = {};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    paddingTop: pxToDp(45),
    backgroundColor: colorScheme.backgroundColorA,
  },
  articleDetali: {
    marginTop: pxToDp(2),
    paddingLeft: pxToDp(15),
    paddingRight: pxToDp(15),
    paddingBottom: pxToDp(15),
    backgroundColor: colorScheme.backgroundColor,
  },
  articleImage: {
    width: '100%',
    minHeight: pxToDp(200),
    marginTop: pxToDp(20),
    marginBottom: pxToDp(20),
  },
  imageModal: {
    width: '100%',
    minHeight: '100%',
  },
  comment: {
    flexDirection: 'row',
    width: '100%',
    paddingLeft: pxToDp(15),
    paddingTop: pxToDp(5),
    paddingRight: pxToDp(15),
    paddingBottom: pxToDp(8),
    backgroundColor: colorScheme.backgroundColorB,
  },
  commentInput: {
    flex: 2,
    height: pxToDp(36),
    padding: 0,
    paddingLeft: pxToDp(18),
    borderRadius: pxToDp(18),
    backgroundColor: colorScheme.backgroundColor,
  },
  like: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  likeIcon: {
    marginRight: pxToDp(5),
    opacity: 0.5,
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(ArticleDetali);
